import React from 'react';
import {
  Icon,
  Tooltip,
  Input,
  Select,
  InputNumber,
  Row,
  Col,
  Button,
  Checkbox,
  Form,
  message,
} from 'antd';
import find from 'lodash/find';
import get from 'lodash/get';
import styles from '../styles.less';
import ComboGrid from '@/pages/Transformer/components/ComboGrid';

function ForNumber({ nodePath, parent, current, dispatch, close, form }) {
  const { getFieldDecorator, validateFields } = form;
  const handleSave = () => {
    validateFields((err, values) => {
      if (!err) {
        const result = [];
        const { min, max, enums, inclueMin, inclueMax, custom } = values;

        const hasMin = typeof min === 'number';

        const hasMax = typeof max === 'number';

        if (hasMin || hasMax) {
          if (max < min) {
            message.error('最大值不能小于最小值');
            return;
          }
          if (min === max) {
            if (!(inclueMin && inclueMax)) {
              message.error('非法的长度限制');
              return;
            }
          }
          const r = { type: 'range' };
          if (hasMin) {
            const key1 = inclueMin ? 'gte' : 'gt';
            r[key1] = min;
          }

          if (hasMax) {
            const key2 = inclueMax ? 'lte' : 'lt';
            r[key2] = max;
          }

          result.push(r);
        }

        if (enums) {
          const arr = enums
            .split('\n')
            .filter(k => k && k.trim())
            .map(k => k.trim());
          result.push({
            type: 'enums',
            enums: arr,
          });
        }

        if (custom && custom.length > 0) {
          result.push({
            type: 'custom',
            ...custom[0],
          });
        }

        dispatch({
          type: 'update_node_rules_attr',
          payload: {
            nodePath,
            current,
            rules: result,
          },
        });

        close();
      }
    });
  };

  const { rules: oldRules = [] } = current;
  const l = find(oldRules, { type: 'range' });
  const e = find(oldRules, { type: 'enums' });
  const c = find(oldRules, { type: 'custom' });

  return (
    <>
      <Row gutter={16} className={styles.advRow}>
        <Col span={12}>
          <Form.Item
            label={
              <>
                最小值&nbsp;
                <Tooltip title="包含最小值">
                  {getFieldDecorator('inclueMin', {
                    valuePropName: 'checked',
                    initialValue: typeof get(l, 'gte') === 'number',
                  })(<Checkbox />)}
                </Tooltip>
              </>
            }
          >
            {getFieldDecorator('min', {
              initialValue: typeof get(l, 'gt') === 'number' ? get(l, 'gt') : get(l, 'gte'),
            })(<InputNumber placeholder="请输入" />)}
          </Form.Item>
        </Col>
        <Col span={12}>
          <Form.Item
            label={
              <>
                最大值&nbsp;
                <Tooltip title="包含最大值">
                  {getFieldDecorator('inclueMax', {
                    valuePropName: 'checked',
                    initialValue: typeof get(l, 'lte') === 'number',
                  })(<Checkbox />)}
                </Tooltip>
              </>
            }
          >
            {getFieldDecorator('max', {
              initialValue: typeof get(l, 'lt') === 'number' ? get(l, 'lt') : get(l, 'lte'),
            })(<InputNumber placeholder="请输入" />)}
          </Form.Item>
        </Col>
      </Row>

      <Row gutter={16} className={styles.advRow}>
        <Col span={24}>
          <Form.Item label="枚举值">
            {getFieldDecorator('enums', {
              initialValue: Array.isArray(get(e, 'enums')) ? get(e, 'enums').join('\n') : '',
            })(
              <Input.TextArea
                placeholder="每行只能写一个值"
                autoSize={{ minRows: 2, maxRows: 6 }}
              />
            )}
          </Form.Item>
        </Col>
      </Row>

      <Row gutter={16} className={styles.advRow}>
        <Col span={24}>
          <Form.Item label="自定义校验规则">
            {getFieldDecorator('custom', {
              initialValue: c ? [c] : [],
            })(
              <ComboGrid
                url="/validation/listCustomValidators"
                method="get"
                popupStyle={{ width: 600 }}
                placeholder="请选择"
                searchPlaceholder="请输入"
                destroyPopupOnHide
                label="title"
                rowKey="className"
                pick="radio"
                columns={[
                  {
                    title: '名称',
                    dataIndex: 'title',
                    ellipsis: true,
                  },
                  {
                    title: '类名',
                    dataIndex: 'className',
                    ellipsis: true,
                  },
                  {
                    title: 'beanName',
                    dataIndex: 'beanName',
                    ellipsis: true,
                  },
                ]}
              />
            )}
          </Form.Item>
        </Col>
      </Row>

      <div className={styles.advFooter}>
        <Button style={{ marginRight: 8 }} onClick={() => close(false)}>
          取消
        </Button>
        <Button type="primary" onClick={() => handleSave()}>
          保存
        </Button>
      </div>
    </>
  );
}

export default Form.create()(ForNumber);
